package com.hjs.test.jst;

import com.jushuitan.api.*;
import com.jushuitan.api.exception.ApiException;
import com.jushuitan.api.util.AuthUtil;

import java.io.IOException;

public class JstProdCaller {
    public static final String API_BASE_URL = "https://openapi.jushuitan.com/";

    public static final String appKey = "2bd1358e1b644b2fb081294baf28d007";
    public static final String appSecret = "f4efd57f1f4d40159de37a4fdeee3364";
    //private static final String initToken = "22b582ec9e654d25825ef59e34592932";
    private static final String initToken = "218dc0c312794f178bda4696040cbf2d";
    private static final String refreshToken = "82c55f6ba3c34922a844536a7ef0cd62";

    public static ApiResponse call(String url,String biz){
        if(!url.startsWith(API_BASE_URL)){
            url = API_BASE_URL + (url.startsWith("/")?url.substring(1):url);
        }
        System.out.println(url);
        ApiClient client = new DefaultApiClient();
        // 构建请求对象
        ApiRequest request = new ApiRequest.Builder(url, appKey, appSecret)
                .biz(biz).build();
        // 执行接口调用
        try {
            ApiResponse response = client.execute(request,initToken);
            //System.out.println("is success: " + response.isSuccess());
            //System.out.println("body: " + response.getBody());
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String refreshToken() {
        AuthRequest request = new AuthRequest.Builder(appKey,appSecret).refreshToken(refreshToken).build();
        try {
            return AuthUtil.refreshToken(request);
        } catch (ApiException e) {
            switch (e.getCodeEnum()) {
                case SYS_ERROR:
                    // TODO retry
                    break;
                case PARAM_ERROR:
                    // TODO check param
                    break;
                case SIGN_ERROR:
                    // TODO @see com.jushuitan.api.util.ApiUtil
                    break;
                case CONNECT_ERROR:
                    // TODO check network
                    break;
                case TIME_OUT_ERROR:
                    // TODO check logic or reset readTimeout
                    break;
                case EXECUTE_ERROR:
                    // TODO @see com.jushuitan.api.DefaultApiClient#executeRemote
                    break;
                default:
                    // log
                    break;
            }
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
